package com.info.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public abstract class SQLHelper
{
    public static Connection conn = DBUtil.Open();
    public static PreparedStatement pstmt;

    public static ResultSet ExecuteReader(String sqlString, Object[] param)
            throws SQLException
    {
        pstmt = conn.prepareStatement(sqlString);
        if (param != null)
        {
            for (int i = 0; i < param.length; i++)
            {
                pstmt.setObject(i + 1, param[i]);
            }
        }
        ResultSet rs = pstmt.executeQuery();
        return rs;
    }

    public static int ExecuteUpdate(String sqlString, Object[] param)
            throws SQLException
    {
        pstmt = conn.prepareStatement(sqlString);
        if (param != null)
        {
            for (int i = 0; i < param.length; i++)
            {
                pstmt.setObject(i + 1, param[i]);
            }
        }
        int i = pstmt.executeUpdate();
        return i;
    }

    //新增封装方法
    public static Integer ExecuteUpdateReturnNewId(String sqlString, Object[] param)
            throws SQLException{
        pstmt = conn.prepareStatement(sqlString,PreparedStatement.RETURN_GENERATED_KEYS);
        if (param != null)
        {
            for (int i = 0; i < param.length; i++)
            {
                pstmt.setObject(i + 1, param[i]);
            }
        }
        int i = pstmt.executeUpdate();

        ResultSet rs = null;
        Integer newId = 0;
        //判断如果受影响的行大于0，说明添加成功
        if(i>0){
            rs = pstmt.getGeneratedKeys();
            if(rs.next()){
                newId = rs.getInt(1);
            }
        }

        return newId;
    }
}